<template>
  <view class="container">
    <!-- 顶部信息区 -->
    <view class="batch-info">
      <view class="batch-number">{{planCode}} 可齐套数量: {{kittingQty}}</view>
      <view class="product-desc">{{designNumberVerSpec}}</view>
    </view>
	<view class="batch-info">
	  <view class="batch-number">{{productBillNo}}</view>
	  <view class="product-desc">{{designNumberVerSpec}}</view>
	</view>
	
	<label>
		<checkbox :value="disable" @tap="handleCheckBox"/>
		是否仅显示有差额数
    </label>
	
    <!-- 表格区域 -->
    <scroll-view scroll-y class="table-container">
		<view class="table-header">
			<view class="table-cell">车间生产任务单/制品</view>
			<view class="table-cell2">计划数</view>
			<view class="table-cell3">差额数</view>
		</view>
		
		<view class="table-body">
			<!-- 表格行数据 -->
			<block v-for="(item, index) in tableRowData" :key="index" >
				<view class="table-ro" 
				:class="{'highlight-row': index === 0, 'selected-row': selectedIndex === index}" 
				v-if="disable ? (item.planQty - item.kittingPointQty > 0) : true"
				@click="selectRow(index)"
				>
					<view class="table-text-name">{{ item.goodsName }}</view>
					<view class="table-row">
						<view class="table-cell.header">{{ item.productBillNo }}</view>
						<view class="table-cell">{{ item.billStatus }}</view>
						<view class="table-cell">{{ item.planQty }}</view>
						<view class="table-cell">{{ item.planQty - item.kittingPointQty }}</view>
					</view>
				</view>
			</block>
		</view>
    </scroll-view>

		<!-- 底部按钮区域 -->
		<view class="bottom-button-area">
			<!-- <button class="action-button">组件齐套</button> -->
			<button class="action-button" @tap="handleDownloadPdf">PDF图纸</button>
			<button class="action-button" @tap="handleWpLoad">工序进度</button>
		</view>
	</view>
	
	<view v-if="maskDisable" class="wp-process-modal">
		<view class="wp-modal-content">
			<view class="wp-modal-header">
				<view class="wp-modal-title">工序进度</view>
				<view class="wp-modal-code">{{ productBillNoSelectd }}</view>
			</view>
			<image
				v-if="imageUrl"
				:src="imageUrl"
				mode="aspectFill"
				lazy-load
				class="wp-image-container"
				@error="handleImageError()"
			/>
			<scroll-view class="wp-table-container">
				<view class="wp-table-header">
					<view class="wp-table-cell">工序</view>
					<view class="wp-table-cell">在制数</view>
					<view class="wp-table-cell">良品数</view>
				</view>
				<block v-for="(item, index2) in tableWpData" :key="index2" >
					<view class="wp-table-row">
						<view class="wp-table-cell process-name">{{ item.wpName }}</view>
						<view class="wp-table-cell">{{ item.inProcessQty }}</view>
						<view class="wp-table-cell">{{ item.goodQty }}</view>
					</view>
				</block>
			</scroll-view>
			<view class="wp-button-group">
				<button class="wp-action-button pdf-button" @tap="handleDownloadPdf">PDF图纸</button>
				<button class="wp-action-button close-button" @tap="handleWpLoad">关闭</button>
			</view>
		</view>
	</view>
	
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { DOWNLOAD_BASE, LAN_URL } from '../config/global';

const GET_QTY_URL = '/kitting/getQty'
const GET_LIST_URL = '/kitting/getList'
const ON_QTY_URL = '/kitting/onQty'
const FILE_URL = '/kitting/getProductPDF'
const GET_PRODUCT_CODE_URL = '/kitting/getProductCode'
const GET_WP_URL = '/kitting/getWpSchedule'
const PIC_URL = '/kitting/getImageUrl'

const router = useRouter();

// 表格数据类型定义
interface TableRow {
	productBillNo: string;      // 生产任务单号
	goodsCode: string;          // 物料编号
	goodsName: string;          // 物料名称
	planQty: number;            // 计划数量
	configureQty: number;       // 配套量
	kittingPointQty: number;    // 齐套数量
	designNumberVerSpec: string;// 设计编号版本规格
	billStatus: string;         // 任务单状态
	billType: string;           // 任务单类型
}

interface TableWp {
	billNo: string;				//生产任务单号
	goodsCode: string;			//物料编号（取缩略图）
	wpName: string;				//工序名称
	inProcessQty: number;		//在制数
	goodQty: number;			//良品数
}

interface FullTableWp {
	goodsCode: string;
	wpNo: number;
	id: number;
	billNo: string;
	wpId: number;
	wpCode: string;
	planQty: number;
	completeQty: number;
	goodQty: number;
	badQty: number;
	setWorkQty: number;
	inProcessQty: number;
	wpName: string;
	goodsName: string;
	designNumber: string;
	notSetWorkQty: number;
}

const planCode = ref('');
const productCode = ref('');
const goodsCode = ref('');
const productBillNo = ref('');
const productBillNoSelectd = ref('');
const kittingQty = ref('');
const designNumberVerSpec = ref('');
const tableRowData = ref<TableRow[]>([]);
const tableWpData = ref<TableWp[]>([]);
const disable = ref(false);
const selectedIndex = ref<number>(-1);
const maskDisable = ref(false);
const imageUrl = ref('');

// 返回上一页
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(() => {
	disable.value = false;
	goodsCode.value = uni.getStorageSync('goodsCode');
	productCode.value = uni.getStorageSync('productCode');
	productBillNo.value = uni.getStorageSync('productBillNo');
	designNumberVerSpec.value = uni.getStorageSync('designNumberVerSpec');
	if(goodsCode.value) {
		getQty();
	}else {
		uni.showToast({
			title: '数据异常',
			icon: 'error'
		})
	}
});
onUnmounted(() => {
    // 组件卸载时：清除存储数据
    uni.removeStorageSync('goodsCode');
    uni.removeStorageSync('productCode');
    uni.removeStorageSync('productBillNo');
    uni.removeStorageSync('designNumberVerSpec');
});

const getQty = () => {
	uni.request({
		url: `${LAN_URL}${GET_QTY_URL}`,
		method: 'POST',
		data: {
			goodsCode: goodsCode.value,
			productCode: productCode.value,
			productBillNo: productBillNo.value
		},success: (res) => {
			console.log(res.data)
			planCode.value = res.data.code;
			kittingQty.value = res.data.qty;
			if(kittingQty.value == null && planCode.value == null) {
				uni.showToast({
					title: '获取数据异常',
					icon: 'error'
				})
				return;
			}else {
				getList();
			}
		},fail() {
			uni.showToast({
				title: '获取数据异常',
				icon: 'none'
			})
		}
	})
}

const getList = () => {
	uni.request({
		url: `${LAN_URL}${GET_LIST_URL}`,
		method: 'POST',
		data: {
			productBillNo: productBillNo.value
		},
		success: (res) => {
		      console.log('获取表格数据成功:', res.data);
		      if (res.data && res.data.length > 0) {
		        tableRowData.value = res.data; // 直接赋值给表格数据
				console.log(tableRowData.value)
				uni.request({
					url: `${LAN_URL}${ON_QTY_URL}`,
					method: 'POST',
					data: {
						productBillNo: productBillNo.value
					},success: (res) => {
						console.log(res.data)
						kittingQty.value = res.data;
					}
				})
		      } else {
		        uni.showToast({
		          title: '未获取到表格数据',
		          icon: 'none'
		        });
		      }
		},
		fail: () => {
		    uni.showToast({
		    title: '网络请求失败',
		    icon: 'none'
		    });
		}
	})
}

/* 获取原始文件名 */
const getFileNameFromUrl = (url: string) => {
  //处理带参数的URL
  const cleanUrl = url.split('?')[0]
  //获取最后一个斜杠后的内容
  const parts = cleanUrl.split('/')
  return parts[parts.length - 1] || `document_${Date.now()}.pdf` // 默认文件名
}
const pdfUrl = ref();
/* 获取物料编号PDF地址 */
const handleDownloadPdf = async () => {
	if(!productBillNoSelectd?.value) {
		uni.showToast({
			title: '无法获取单号',
			icon: 'error'
		})
		return;
	}
	uni.request({
		url: `${LAN_URL}${FILE_URL}`,
		method: 'POST',
		data: {
			productCode: productBillNoSelectd.value
		},success:(res) => {
			if(res.statusCode === 200) {
				pdfUrl.value = res.data
				console.log(pdfUrl.value)
				downloadPdf();
			}else {
				uni.showToast({
					title: '文件不存在',
					icon: 'none'
				})
			}
			
		},fail() {
			uni.showToast({
				title: '没有该数据',
				icon: 'none'
			})
		}
	});
}
/* PDF下载 */
const downloadPdf = async () => {
	if(!pdfUrl.value || !pdfUrl.value.trim()) {
		uni.showToast({
			title: '无法找到文件',
			icon: 'none'
		})
		return;
	}
	pdfUrl.value = pdfUrl.value ? `${DOWNLOAD_BASE}${pdfUrl.value}` : undefined
	try {
		const fileName = getFileNameFromUrl(pdfUrl.value)
		const saveDir = '_doc/uniapp_save/'
		
		const { tempFilePath } = await uni.downloadFile({
			url: pdfUrl.value
		})
		let savedPath = '';
		
		// #ifdef MP-WEIXIN
		savedPath = `${uni.env.USER_DATA_PATH}/${Date.now()}.pdf`
		// #endif
	
		// #ifdef APP-PLUS
		savedPath = `${plus.io.convertLocalFileSystemURL(saveDir)}${fileName}`
		// #endif
		uni.openDocument({
			filePath: savedPath,
			success: () => {
			    console.log("PDF文件已成功不下载打开");
			},
			fail() {
				uni.saveFile({
					tempFilePath, filePath: savedPath, success(res) {
						console.log("res:" + res.savedFilePath)
						plus.io.resolveLocalFileSystemURL(res.savedFilePath,
							(entry) => {
								console.log("实际存储路径:", "fullPath" + entry.fullPath);
								console.log("savedPath:",savedPath)
								//重命名文件
								plus.io.resolveLocalFileSystemURL(saveDir, (dirEntry) => {
								    entry.moveTo(dirEntry, fileName, (newEntry) => {
								        console.log("文件已重命名:", newEntry.fullPath);
									}, (err) => {
										console.error("文件重命名失败:", err);
									});
								});
							}, 
							(err) => {
								console.log("找不到文件:", err);
							}
						);
						uni.openDocument({
							filePath: res.savedFilePath,
							success: () => {
								console.log("PDF文件已成功打开");
							},
							fail: (err) => {
								console.error("PDF打开失败:", err);
							}
						});
					},fail(err) {
						uni.showToast({ title: '文件不存在', icon: 'error' })
						console.log(err)
					}
				})
			}
		})
	} catch (error) {
		uni.showToast({ title: '文件打开失败', icon: 'none' })
	}
}
const handleCheckBox = () => {
	if(disable.value){
		disable.value = false;
	}else {
		disable.value = true;
	}
	if(goodsCode.value) {
		getQty();
	}else {
		uni.showToast({
			title: '数据异常',
			icon: 'error'
		})
	}
};
const selectRow = (index: number) => {
	selectedIndex.value = index;
	if(productBillNo) {
		productBillNoSelectd.value = tableRowData.value[index].productBillNo
		//goodsCode.value = tableRowData.value[index].goodsCode
		console.log(productBillNoSelectd.value)
	}else {
		console.log("e")
	}
}
/* 组件齐套
const underDetail = () => {
	uni.request({
		url: `${LAN_URL}${GET_PRODUCT_CODE_URL}`,
		method: 'POST',
		data: {
			productBillNo: productBillNo.value
		},success: (res) => {
			productCode.value = res.data
			getQty();
		}
	})
}
*/
const handleWpLoad = () => {
	if(maskDisable.value){
		maskDisable.value = false;
		tableWpData.value = [];
		imageUrl.value = '';
		console.log(tableWpData);
		return;
	}
	uni.request({
		url: `${LAN_URL}${GET_WP_URL}`,
		method: 'POST',
		data: {
			billNo: productBillNoSelectd.value
		},
		success: (res) => {
			console.log('获取表格数据成功2:', res.data);
			if(res.data && res.data.length > 0) {
				tableWpData.value = res.data
				uni.request({
					url: `${LAN_URL}${PIC_URL}`,
					method: 'POST',
					data: {
						goodsCode: tableWpData.value[1].goodsCode
					},
					success: (res2) => {
						imageUrl.value = res2.data ? `${DOWNLOAD_BASE}${res2.data}` : undefined;
					}
				})
				maskDisable.value = true;
			}else {
				uni.showToast({
					title: '无法找到数据',
					icon: 'none'
				})
			}
		},fail() {
			uni.showToast({
				title: '数据异常',
				icon: 'none'
			})
		}
	})
}

const handleImageError = () => {
	imageUrl.value = '/static/images/placeholder.png'
}

</script>

<style scoped lang="scss">
page {
  background-color: #f5f5f5;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #007AFF;
  color: white;
  position: relative;

  .back-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .title {
    font-size: 34rpx;
    font-weight: 500;
  }
}

/* 顶部信息区样式 */
.batch-info {
	padding: 20rpx 30rpx;
	background-color: #ffffff;
	color: black;
	border: 1px solid #e0e0e0;  /* 实线细边框 */
	//border-radius: 4px;

  .batch-number {
    font-size: 30rpx;
    margin-bottom: 10rpx;
  }

  .product-desc {
    font-size: 28rpx;
  }
}

/* 表格容器样式 */
.table-container {
  flex: 1;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: white;
}

/* 表格头部样式 */
.table-header {
	display: flex;
	height: 80rpx;
	line-height: 80rpx;
	background-color: #F5F5F5;
	border-bottom: 1rpx solid #E5E5E5;

	.table-cell {
		flex: 1;
		text-align: center;
		font-weight: 100%;
		font-size: 28rpx;
		white-space: nowrap;       /* 禁止换行 */
		//overflow: hidden;
		//text-overflow: ellipsis;
	
		.header {
			width: 100%;
			font-size: 28rpx;
		}
	}
	.table-cell2 {
		flex: 1;
		width: 100%;
		text-align: center;
		font-size: 28rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-left: 160rpx;
	}
	.table-cell3 {
		flex: 1;
		width: 100%;
		text-align: center;
		font-size: 28rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		margin-left: -5rpx;
	}
}

/* 表格行样式 */
.table-body {
	 padding-bottom: 120rpx;
	.table-row {
		margin-top: -30rpx;
		display: flex;
		flex: 1;
		height: 120rpx;
		line-height: 120rpx;
		border-bottom: 1rpx solid #E5E5E5;

		&:last-child {
			border-bottom: none;
		}

		&.highlight-row {
			background-color: #F0F9FF;
		}

		.table-cell {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			padding: 0 10rpx;

			&.ellipsis {
				text-align: left;
			}
		}
	}
	
	.table-text-name {
		display: flex;
		font-size: 24rpx;
		margin-top: 20rpx;
		margin-left: 20rpx;
		flex: 2;
	}
}
.selected-row {
  background-color: #5555ff; /* 浅蓝色背景，可以根据需要调整 */
  color: white;
  /* 可以添加其他选中效果的样式，如边框等 */
}


/* 底部按钮区域样式 */
.bottom-button-area {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	display: flex;
	justify-content: space-between;
	padding: 0 30rpx;
	background-color: white;
	border-top: 1rpx solid #E5E5E5;

	.action-button {
		height: 80rpx;
		line-height: 80rpx;
		background-color: #FF6B6B;
		color: white;
		font-size: 28rpx;
		border-radius: 40rpx;
		margin-top: 10rpx;
  }
}


/* 工序进度悬浮框 */
.wp-process-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.wp-modal-content {
  width: 90%;
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 80vh; /* 限制最大高度 */
}

.wp-modal-header {
  background-color: #409EFF;
  color: white;
  padding: 15px;
  text-align: center;
}

.wp-modal-title {
  font-size: 18px;
  font-weight: bold;
  display: block;
}

.wp-modal-code {
  font-size: 14px;
  display: block;
}

/* 修改图片容器样式 */
.wp-image-container {
  height: 120px; /* 调整为更合适的高度 */
  background-color: #f0f0f0;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 重新设计表格布局 */
.wp-table-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 10px; /* 添加内边距 */
}

/* 使用类似HTML表格的布局 */
.wp-table-header, .wp-table-row {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.wp-table-header {
  background-color: #f5f7fa;
  font-weight: 500;
}

.wp-table-cell {
  padding: 0 10px;
  font-size: 14px;
}

/* 工序名称左对齐，其他居中 */
.wp-table-cell:first-child {
  flex: 2; /* 工序列更宽 */
  text-align: left;
  padding-left: 15px;
}

.wp-table-cell:nth-child(2),
.wp-table-cell:nth-child(3) {
  flex: 1; /* 数字列较窄 */
  text-align: center;
}

.process-name {
  text-align: left;
}

/* 按钮组样式调整 */
.wp-button-group {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ebeef5;
}

.wp-action-button {
  flex: 1;
  padding: 8px 0;
  margin: 0 5px;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  border: 1px solid #dcdfe6; /* 添加边框 */
}

.pdf-button {
  background-color: #f5f7fa;
}

.close-button {
  background-color: #f5f7fa;
}
</style>